package org.dync.giftlibrary.util.glide;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.render.PixelMapShader;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;
import org.jetbrains.annotations.NotNull;

import java.security.MessageDigest;

/**
 * Created by Skyline on 2016/5/24.
 */
public class GlideCircleTransform extends BitmapTransformation {
    @Override
    protected PixelMap transform(@NotNull BitmapPool bitmapPool, @NotNull PixelMap pixelMap, int i, int i1) {
        return circleCrop(bitmapPool, pixelMap);
    }

    private static PixelMap circleCrop(BitmapPool pool, PixelMap source) {
        if (source == null) return null;

        int size = Math.min(source.getImageInfo().size.width, source.getImageInfo().size.height);
        int x = (source.getImageInfo().size.width - size) / 2;
        int y = (source.getImageInfo().size.height - size) / 2;

        // TODO this could be acquired from the pool too
        PixelMap squared = PixelMap.create(source, new Rect(x, y, size, size), new PixelMap.InitializationOptions());

        PixelMap result = pool.get(size, size, PixelFormat.ARGB_8888);
        if (result == null) {
            result = PixelMap.create(createOpts(size, size, PixelFormat.ARGB_8888));
        }

        Canvas canvas = new Canvas();
        Paint paint = new Paint();
        PixelMapShader pixelMapShader = new PixelMapShader(new PixelMapHolder(squared), PixelMapShader.TileMode.CLAMP_TILEMODE, PixelMapShader.TileMode.CLAMP_TILEMODE);
        paint.setShader(pixelMapShader, Paint.ShaderType.LINEAR_SHADER);
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);
        return result;
    }

    public String getId() {
        return getClass().getName();
    }

    @Override
    public void updateDiskCacheKey(MessageDigest messageDigest) {
        messageDigest.update(getId().getBytes());
    }

    public static PixelMap.InitializationOptions createOpts(int width, int height, PixelFormat pixelFormat) {
        PixelMap.InitializationOptions initOptions = new PixelMap.InitializationOptions();
        initOptions.pixelFormat = pixelFormat;
        initOptions.size = new Size(width, height);
        initOptions.editable = true;
        return initOptions;
    }
}

